# -*- coding:utf-8 -*-
"""
脚本执行现象: 脚本程序下载成功后，手机端使用蓝牙调试助手与ESP32模块进行数据的收发
注意事项：
无
"""

# 导入模块
from machine import Pin
from machine import Timer
from time import sleep_ms
import bluetooth
from open_door import DoorController  # 导入 DoorController 类
from identify import RFIDHandler
import time
import _thread

# 定义全局变量
BLE_MSG = ""
DOOR_MODE = 'CLOSED'  # 初始模式为关闭

class ESP32_BLE:
    def __init__(self, name):
        self.led = Pin(2, Pin.OUT)  # LED引脚
        self.door_controller = DoorController(12)  # 门控制引脚，使用GPIO 12
        self.timer1 = Timer(0)
        self.name = name

        self.ble = bluetooth.BLE()
        self.ble.active(True)
        self.ble.config(gap_name=name)
        self.disconnected()
        self.ble.irq(self.ble_irq)
        self.register()
        self.advertiser()

    def connected(self):
        self.led.value(1)  # 连接时LED常亮
        self.timer1.deinit()

    def disconnected(self):
        self.timer1.init(period=1000, mode=Timer.PERIODIC, callback=lambda t: self.led.value(not self.led.value()))
        self.door_controller.door_pin.value(0)  # 确保门是关闭的

    def ble_irq(self, event, data):
        global BLE_MSG
        if event == 1:  # 连接事件
            self.connected()
        elif event == 2:  # 断开事件
            self.advertiser()
            self.disconnected()
        elif event == 3:  # 数据写入事件
            buffer = self.ble.gatts_read(self.rx)
            BLE_MSG = buffer.decode('UTF-8').strip()
            print("接收到其他蓝牙终端发来的数据:", BLE_MSG)

            # 处理接收到的指令
            self.handle_command(BLE_MSG)

    def register(self):
        service_uuid = '6E400001-B5A3-F393-E0A9-E50E24DCCA9E'
        reader_uuid = '6E400002-B5A3-F393-E0A9-E50E24DCCA9E'
        sender_uuid = '6E400003-B5A3-F393-E0A9-E50E24DCCA9E'
        services = (
            (
                bluetooth.UUID(service_uuid),
                (
                    (bluetooth.UUID(sender_uuid), bluetooth.FLAG_NOTIFY),
                    (bluetooth.UUID(reader_uuid), bluetooth.FLAG_WRITE),
                )
            ),
        )
        ((self.tx, self.rx),) = self.ble.gatts_register_services(services)

    def send(self, data):
        self.ble.gatts_notify(0, self.tx, data + '\n')

    def advertiser(self):
        name = bytes(self.name, 'UTF-8')
        adv_data = bytearray('\x02\x01\x02', 'UTF-8') + bytearray((len(name) + 1, 0x09), 'UTF-8') + name
        self.ble.gap_advertise(100, adv_data)
        print("广告数据:", adv_data)
        print("\r\n")

    def handle_command(self, command):
        global DOOR_MODE
        if command == "OPEN":
            if DOOR_MODE == 'CLOSED':
                self.door_controller.open_door()  # 调用开门逻辑
            else:
                print("门已经处于常开模式，无需再次打开。")
        elif command == "CLOSE":
            self.close_door()
        elif command == "TOGGLE_MODE":
            if DOOR_MODE == 'CLOSED':
                DOOR_MODE = 'OPEN'
                self.door_controller.open_mode()  # 调用常开逻辑
                print("门模式已切换为: 常开")
            else:
                DOOR_MODE = 'CLOSED'
                self.door_controller.close_mode()  # 调用常闭逻辑
                print("门模式已切换为: 常闭")
        print("当前门模式:", DOOR_MODE)

    def close_door(self):
        print("关闭门...")
        self.door_controller.door_pin.value(0)  # 关闭门

def start_bluetooth_service(ble_name):
    # 启动蓝牙服务
    ble = ESP32_BLE(ble_name)
    while True:
        time.sleep(1)  # 保持蓝牙服务运行

def main():
    global DOOR_MODE  # 允许在主函数中修改 DOOR_MODE

    # 初始化RFID读卡器，引脚配置
    sck = 0
    mosi = 2
    miso = 4
    rst = 5
    cs = 14
    
    # 初始化开门控制器，引脚为12 (可以根据实际硬件调整)
    door_gpio_pin = 12
    door_controller = DoorController(door_gpio_pin)
   
    # 期望数据 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
    expected_data = list(range(16))

    # 启动蓝牙服务的线程
    _thread.start_new_thread(start_bluetooth_service, ("ESP32_DoorController",))

   

    # 循环等待刷卡
    while True:
        # 创建RFID处理对象
        rfid_handler = RFIDHandler(sck, mosi, miso, rst, cs)
        # 检查门的状态
        if DOOR_MODE == 'OPEN':
            print("门处于常开模式，RFID 刷卡功能已禁用。")
            time.sleep(1)
            continue

        print("等待RFID卡刷卡验证...")

        # 验证RFID卡片
        if rfid_handler.read_and_validate_block(2, expected_data):
            print("验证通过，执行开门操作...")
            door_controller.open_door()
        else:
            print("验证失败，请重试...")
        
        # 暂停一小段时间，避免过度刷卡
        time.sleep(1)

if __name__ == '__main__':
    main()
